#include "ScenarioPanel.h"

ScenarioPanel::ScenarioPanel(std::string scenarioName, int xPos, int yPos,
		Widget* parent) :
		Container(xPos, yPos, parent) {

	parcel = getPosition();
	panel = NULL;
	this->scenarioName = scenarioName;
}

void ScenarioPanel::updateBackground(std::string background) {
	this->background = background;
	panel = loadSurface(background);
	parcel.height = panel->h;
	parcel.width = panel->w;
	resize(800, 600);

}

std::string ScenarioPanel::getScenarioName() const {
	return this->scenarioName;
}


void ScenarioPanel::setElements(std::list<Widget*> scenaryElements) {
	Widget* element = NULL;
	std::list<Widget*>::iterator it_aux;
	for (it_aux = scenaryElements.begin(); it_aux != scenaryElements.end();
			++it_aux) {
		element = (*it_aux);

		//TODO los widgets deberian tener parents!!
		//element->setParent(this);

		this->elements.push_back(element);

		add(element);
	}
}

ScenarioPanel::~ScenarioPanel() {
	if (panel != NULL) {
		SDL_FreeSurface(panel);
	}
}

void ScenarioPanel::handleEvent(Event event) {
	for (it_widget = widgets.begin(); it_widget != widgets.end(); ++it_widget) {
		((Widget*) *it_widget)->handleEvent(event);
	}
}

void ScenarioPanel::resolve() {
	for (it_widget = widgets.begin(); it_widget != widgets.end(); ++it_widget) {
		((Widget*) *it_widget)->resolve();
	}
}

void ScenarioPanel::showOn(SDL_Surface *surface) {
	SDL_Rect rect;
	rect.x = parcel.posX;
	rect.y = parcel.posY;
	rect.w = parcel.width;
	rect.h = parcel.height;

	SDL_BlitSurface(panel, NULL, surface, &rect);

	for (it_widget = widgets.begin(); it_widget != widgets.end(); ++it_widget) {
		((Widget*) *it_widget)->showOn(surface);
	}
}

void ScenarioPanel::resize(int w, int h) {
	if (parcel.width != w || parcel.height != h) {
		SDL_Surface* surface2 = new SDL_Surface();
		double zoomw = ((double) w) / ((double) parcel.width);
		double zoomh = ((double) h) / ((double) parcel.height);
		surface2 = zoomSurface(this->panel, zoomw, zoomh, SMOOTHING_OFF);
		SDL_FreeSurface(this->panel);
		this->panel = surface2;
		parcel.height = panel->h;
		parcel.width = panel->w;
	}

}
